package com.atguigu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.SkuEsModel;
import com.atguigu.gulimall.search.config.GulimallElasticsearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ElasticSearchService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {


    @Autowired
    RestHighLevelClient highLevelClient;

    @Override
    public boolean saveProduct(List<SkuEsModel> esModels) {
        BulkRequest bulkRequest=new BulkRequest();
        for (SkuEsModel es:esModels) {
            IndexRequest request=new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(es.getSkuId().toString());
            request.source(JSON.toJSONString(es), XContentType.JSON);
            bulkRequest.add(request);
        }

        BulkResponse bulk = null;
        try {
            bulk = highLevelClient.bulk(bulkRequest, GulimallElasticsearchConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


        if (!bulk.hasFailures()){
            List<Integer> collect = Arrays.stream(bulk.getItems()).map(BulkItemResponse::getItemId).collect(Collectors.toList());
        }
        if (bulk.hasFailures()) {
            throw new RuntimeException("上架出现异常");
        }
        return bulk.hasFailures();
    }
}
